class Solution {
    vector<int> index;//记录nums当前的固定的原始下标
    vector<int> ret;//最后返回的统计结果
    int tmpNum[500010];
    int tmpIndex[500010];
public:
    vector<int> countSmaller(vector<int>& nums) {
        ret.resize(nums.size());
        index.resize(nums.size());
        for(int i=0;i<nums.size();i++)
        {
            index[i]=i;
        }
        mySort(nums,0,nums.size()-1);
        return ret;
    }
    void mySort(vector<int>& nums,int left,int right)
    {
        if(left>=right) return;
        int mid=(right+left)>>1;
        mySort(nums,left,mid);
        mySort(nums,mid+1,right);
        int cur1=left,cur2=mid+1,i=0;
        while(cur1<=mid&&cur2<=right)
        {
            if(nums[cur1]>nums[cur2])
            {
                ret[index[cur1]]+=right-cur2+1;//重点
                tmpNum[i]=nums[cur1];
                tmpIndex[i++]=index[cur1++];
            }
            else
            {
                tmpNum[i]=nums[cur2];
                tmpIndex[i++]=index[cur2++];
            
            }
        }
        while(cur1<=mid) 
        {
            tmpNum[i]=nums[cur1];
            tmpIndex[i++]=index[cur1++];
        }
        while(cur2<=right)
        {
            tmpNum[i]=nums[cur2];
            tmpIndex[i++]=index[cur2++];
        }

        for(int j=left;j<=right;j++)
        {
            nums[j]=tmpNum[j-left];
            index[j]=tmpIndex[j-left];
        }
    }
};
